package org.example.admin.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.admin.dto.UserRoleIdListDto;
import org.example.admin.dto.UserRoleListDto;
import org.example.admin.service.AdminUserService;
import org.example.common.utils.ResponseUtil;
import org.example.db.entity.Role;
import org.example.db.entity.User;
import org.example.db.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admin/user")
@Api(tags = "对用户的操作")
public class AdminUserController {

    AdminUserService adminUserService;

    public AdminUserController(AdminUserService adminUserService) {
        this.adminUserService = adminUserService;
    }


    @GetMapping("/list")
    @ApiOperation("获取用户数据")
    public Object getUserListPage(){
        return ResponseUtil.ok(adminUserService.getAdminUserList());
    }

    @PostMapping("/add")
    @ApiOperation("增加一个用户")
    public Object addUser(@RequestBody User user){

        adminUserService.addUser(user);
        return ResponseUtil.ok();
    }

    @PostMapping("/update")
    public Object addUser(@RequestBody UserRoleIdListDto userRoleIdListDto){

        User user = userRoleIdListDto.getUser();
        adminUserService.updateUser(user);

        Long UserId = userRoleIdListDto.getUser().getId();
        adminUserService.deleteRoleById(UserId);
        List<Long> roleIds = userRoleIdListDto.getRoleIdList();
        for (Long roleId:roleIds) {
            adminUserService.addRoleUser(UserId,roleId);
        }
        return ResponseUtil.ok();

    }

    @PostMapping("/delete")
    public Object deleteUserRole(@RequestBody UserRoleListDto userRoleListDto){

        User user = userRoleListDto.getUser();
        adminUserService.deleteRoleById(user.getId());
        adminUserService.deleteUser(user.getId());
        return ResponseUtil.ok();
    }

    @PostMapping("/create")
    public Object addUserRole(@RequestBody UserRoleIdListDto userRoleIdListDto){

        User user = userRoleIdListDto.getUser();
        adminUserService.addUser(user);

        Long UserId = user.getId();
        List<Long> roleIds = userRoleIdListDto.getRoleIdList();
        for (Long roleId:roleIds) {
            adminUserService.addRoleUser(UserId,roleId);
        }
        return ResponseUtil.ok();
    }

}
